package org.jeecg.modules.miniAppCustomerEndPoint.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.miniAppCustomerEndPoint.constant.JxCustomerConstant;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

@Slf4j
public class JxUserUtil {

    public static String getUserId(String token , String userIdForDebug) {
        DecodedJWT jwt = JWT.decode(token);
        String userIdFromToken = jwt.getClaim("username").asString();
        String userId = null;
        // 若用于调试的请求参数 userId 为null或空字符串，则使用从 token中解码出来的 用户id
        if (userIdForDebug == null || userIdForDebug.isEmpty()) {
            userId = userIdFromToken.replace(JxCustomerConstant.JX_USER_LOGIN_TOKEN, "");
        } else {
            userId = userIdForDebug;
        }

        return userId;
    }

    public static String formateDateTimeYYYYMMDDHHMMSS(Date dateTime) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatedDate = sdf.format(dateTime);

        return formatedDate;
    }

    public static String localDateTime2YYYYMMDDHHMMSS(LocalDateTime localDateTime) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        //时区的日期和时间
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
        //获取时刻
        Date date = Date.from(zonedDateTime.toInstant());
        String formatedDate = sdf.format(date);

        return formatedDate;

    }

    public static String formateHHMMSS(Date dateTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String formatedDate = sdf.format(dateTime);

        return formatedDate;
    }

    public static Date parseDateFromHHMMSS(String hhMMssTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            Date date = sdf.parse(hhMMssTime);
            return date;
        } catch (ParseException e) {
            log.error("parseTimeFromHHMMSS error: {}", e);
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        System.out.println(calendar.getTime().toString());
    }

}
